<script setup>
import {
  UserFilled,
  User,
  Crop,
  EditPen,
  SwitchButton,
  CaretBottom
} from '@element-plus/icons-vue'
import avatar from '@/assets/default.png'
import {useRouter} from 'vue-router'
import {ElMessage, ElMessageBox} from 'element-plus'
import {useTokenStore} from '@/stores/token.js'
import {userLogoutService} from '@/api/user.js'
import {computed, ref, markRaw, onMounted} from 'vue'
import menusInfoStore from '@/stores/menu.js'
import * as ElementPlusIcons from '@element-plus/icons-vue'
import useMenuInfoStore from "@/stores/userInfo.js";

// 预加载所有视图组件
const viewModules = import.meta.glob('@/view/**/*.vue')

const router = useRouter()
const tokenStore = useTokenStore()
const menuInfoStore = menusInfoStore()
const userInfo = useMenuInfoStore()

// 检查token并初始化页面
onMounted(() => {
  if (!tokenStore.token) {
    router.push('/login')
    return
  }
  // 如果需要在页面加载时进行其他初始化操作，可以在这里添加
})

// 当前活动菜单
const activeMenu = ref('')
// 当前显示的组件
const currentView = ref(null)
// 图标映射处理
const iconMap = {}
Object.entries(ElementPlusIcons).forEach(([key]) => {
  // 转换图标名称格式（例如：el-icon-monitor -> Monitor）
  const iconName = key.replace('el-icon-', '').replace(/(?:^|-)(\w)/g, (_, c) => c.toUpperCase())
  iconMap[`el-icon-${key.replace('el-icon-', '').toLowerCase()}`] = ElementPlusIcons[key]
})

// 处理菜单结构
const menuList = computed(() => {
  const menus = menuInfoStore.menusInfo || []
  if (!Array.isArray(menus)) return []

  const filteredMenus = menus
      .filter(menu => !menu.hidden)
      .sort((a, b) => a.orderNum - b.orderNum)

  // 创建层级结构
  const menuMap = new Map()
  filteredMenus.forEach(menu => {
    menu.children = []
    menuMap.set(menu.menuId, menu)
  })

  const topLevelMenus = []
  filteredMenus.forEach(menu => {
    if (menu.parentMenuId) {
      const parent = menuMap.get(menu.parentMenuId)
      parent?.children.push(menu)
    } else {
      topLevelMenus.push(menu)
    }
  })

  return topLevelMenus
})

// 路径拼接方法
const resolvePath = (basePath, childPath) => {
  if (!basePath) return childPath
  if (!childPath) return basePath
  return `${basePath}/${childPath}`.replace(/\/+/g, '/')
}

// 处理菜单点击
const handleMenuClick = async (index) => {
  activeMenu.value = index
  try {
    // 构建组件路径
    const componentPath = `/src/view${index}.vue`
    const module = viewModules[componentPath]
    if (!module) {
      throw new Error(`找不到组件: ${componentPath}`)
    }
    const component = await module()
    currentView.value = markRaw(component.default)
  } catch (error) {
    console.error('加载组件失败:', error)
    ElMessage.error('页面加载失败')
  }
}

// 退出登录逻辑
const handleCommand = async (command) => {
  if (command === 'logout') {
    try {
      await ElMessageBox.confirm(
          '你确认退出登录吗？',
          '温馨提示',
          {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning'
          }
      )
      // 先调用退出接口
      await userLogoutService()
      // 再清除本地存储
      menuInfoStore.removeMenusInfo()
      userInfo.removeUserInfo()
      tokenStore.removeToken()
      // 最后跳转
      ElMessage.success('退出成功')
      await router.push('/login')
    } catch (error) {
      await router.push('/login')
    }
  } else {
    // 处理用户信息相关的点击
    const path = `/user/${command}`
    await handleMenuClick(path)
  }
}
</script>

<template>
  <el-container class="layout-container">
    <!-- 左侧菜单 -->
    <el-aside width="200px">
      <div class="el-aside__logo"></div>
      <el-menu
          active-text-color="#000000"
          background-color="#757171"
          text-color="#fff"
          :default-active="activeMenu"
          @select="handleMenuClick"
      >
        <template v-for="menu in menuList" :key="menu.menuId">
          <el-sub-menu
              v-if="menu.children?.length"
              :index="resolvePath(menu.path, '')"
          >
            <template #title>
              <el-icon v-if="menu.icon">
                <component :is="iconMap[menu.icon]" />
              </el-icon>
              <span>{{ menu.menuName }}</span>
            </template>
            <el-menu-item
                v-for="child in menu.children"
                :key="child.menuId"
                :index="resolvePath(menu.path, child.path)"
            >
              <el-icon v-if="child.icon">
                <component :is="iconMap[child.icon]" />
              </el-icon>
              <span>{{ child.menuName }}</span>
            </el-menu-item>
          </el-sub-menu>

          <el-menu-item
              v-else
              :index="menu.path"
          >
            <el-icon v-if="menu.icon">
              <component :is="iconMap[menu.icon]" />
            </el-icon>
            <span>{{ menu.menuName }}</span>
          </el-menu-item>
        </template>

        <!-- 固定个人中心菜单 -->
        <el-sub-menu index="personal">
          <template #title>
            <el-icon><UserFilled /></el-icon>
            <span>个人中心</span>
          </template>
          <el-menu-item index="/user/info">
            <el-icon><User /></el-icon>
            <span>基本资料</span>
          </el-menu-item>
          <el-menu-item index="/user/avatar">
            <el-icon><Crop /></el-icon>
            <span>更换头像</span>
          </el-menu-item>
          <el-menu-item index="/user/password">
            <el-icon><EditPen /></el-icon>
            <span>重置密码</span>
          </el-menu-item>
        </el-sub-menu>
      </el-menu>
    </el-aside>

    <!-- 右侧主区域 -->
    <el-container>
      <el-header>
        <div>用户<strong>{{ userInfo.userInfo?.fullName }}</strong></div>
        <el-dropdown placement="bottom-end" @command="handleCommand">
          <span class="el-dropdown__box">
            <el-avatar :src="userInfo.userInfo?.imgUrl || avatar" alt="用户头像" />
            <el-icon><CaretBottom /></el-icon>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="info" :icon="User">基本资料</el-dropdown-item>
              <el-dropdown-item command="avatar" :icon="Crop">更换头像</el-dropdown-item>
              <el-dropdown-item command="password" :icon="EditPen">重置密码</el-dropdown-item>
              <el-dropdown-item command="logout" :icon="SwitchButton">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </el-header>

      <el-main class="main-content">
        <component :is="currentView" v-if="currentView"></component>
        <div v-else class="empty-content">
          <el-empty description="请选择一个菜单项"></el-empty>
        </div>
      </el-main>

      <el-footer>校园设备管理 2025 Created by xk</el-footer>
    </el-container>
  </el-container>
</template>

<style lang="scss" scoped>
.layout-container {
  height: 100vh;

  .el-aside {
    background-color: #757171;
    height: 100%;

    &__logo {
      height: 60px;
      background: url('@/assets/logo.png') no-repeat center / contain;
      margin: 10px 0;
    }

    .el-menu {
      border-right: none;

      :deep(.el-sub-menu__title),
      :deep(.el-menu-item) {
        &:hover {
          background-color: rgba(255, 255, 255, 0.1);
        }
      }
    }
  }

  .el-header {
    background-color: #fff;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .el-dropdown__box {
      display: flex;
      align-items: center;

      .el-icon {
        color: #999;
        margin-left: 10px;
      }
    }
  }

  .el-main {
    height: calc(100% - 64px - 50px);
    padding: 20px;
  }

  .el-footer {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 14px;
    color: #666;
    height: 50px;
  }
}
</style>
